/*
 * @Author: 汪誉恒 1063642059@qq.com
 * @Date: 2022-05-20 20:11:13
 * @LastEditors: 汪誉恒 1063642059@qq.com
 * @LastEditTime: 2022-06-18 18:06:38
 * @FilePath: \wui-next\vite.config.ts
 * @Description: 
 * 
 * Copyright (c) 2022 by 汪誉恒 1063642059@qq.com, All Rights Reserved. 
 */
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { md } from './src/plugins/md'
import { baseParse, ElementNode } from '@vue/compiler-core'
import { searchTagContent } from './src/plugins/code'
import fs from 'fs'

type FindElementType = {
  tag: string;
} & ElementNode;
const saDemoParse = {
  name: 'sa-demo-parse',
  transform(code: string, id: string) {
    if (!/vue&type=demo/.test(id)) return;
    const title = searchTagContent(code, 'title') || code;
    const file = fs.readFileSync(id.split('?')[0]).toString();
    const parsed = baseParse(file).children.find((n: FindElementType) => n.tag === 'demo');
    const main = file.split(parsed.loc.source).join('').trim();
    const sourceCode = main;
    return `export default Comp => {
      Comp.__sourceCode = ${JSON.stringify(sourceCode)}
      Comp.__sourceCodeTitle = ${JSON.stringify(title)}
    }`;
  },
};

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [md(), vue(), saDemoParse],
  build: {
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      }
    }
  }
})
